package com.zhongyw.mvt.gis.controllers;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.zhongyw.mvt.gis.entity.Result;
import com.zhongyw.mvt.gis.service.IShapefileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


/**
 * @author zhong
 */
@RestController
@Api(tags="空间分析")
@RequestMapping("/spatial")
@Slf4j
public class SpatialController {
	@Autowired
	private IShapefileService iShapefileService;

	/**
	 * 叠加分析 - 获取两个空间数据的交集
	 *
	 * @param layer1 第一个图层名称
	 * @param layer2 第二个图层名称
	 * @return 返回叠加分析的结果
	 */
	@ApiOperationSupport(author = "2385601060@qq.com")
	@GetMapping("/overlay/intersection")
	@ApiOperation(value = "淹没分析", notes = "根据图层名称进行叠加分析")
	public Result<List<Map<String, Object>>> overlayIntersection(
			@RequestParam(name = "layer1", defaultValue = "居民点") String layer1,
			@RequestParam(name = "layer2", defaultValue = "淹没数据") String layer2) {
		log.info("开始叠加分析: layer1={}, layer2={}", layer1, layer2);

		List<Map<String, Object>> results = iShapefileService.getIntersection(layer1, layer2);

		ObjectMapper mapper = new ObjectMapper();

		try {
			for (Map<String, Object> result : results) {
				if (result.containsKey("geom")) {
					String geomStr = (String) result.get("geom");
					// 将 geom 字符串解析为 Map（自动去除转义）
					Map<String, Object> geomJson = mapper.readValue(geomStr, Map.class);
					result.put("geom", geomJson); // 替换原来的字符串为真正的 JSON 对象
				}
			}
		} catch (Exception e) {
			log.error("解析 geom 失败", e);
			return Result.error("几何字段解析失败：" + e.getMessage());
		}

		log.info("叠加分析结果: {}", results);
		return Result.ok(results);
	}

	@ApiOperationSupport(author = "2385601060@qq.com")
	@GetMapping("/nearest")
	@ApiOperation(value = "近邻分析", notes = "查找指定图层中与给定几何对象最近的对象")
	public Result<?> nearestNeighbor(
			@RequestParam(name = "layer", defaultValue = "避灾点") String layer,
			@RequestParam(name = "geoJson", defaultValue = "{\"type\": \"Point\",\"crs\": {\"type\": \"name\",\"properties\": {\"name\": \"EPSG:3857\"}},\"coordinates\": [1.3209393705935262E7,3772240.102524894]}") String geoJson) {
		log.info("开始近邻分析: layer={}, geoJson={}", layer, geoJson);
		List<Map<String, Object>> results = iShapefileService.nearestNeighbor(layer,geoJson);
		log.info("近邻分析结果: {}", results);
		return Result.ok(results);
	}

	@ApiOperationSupport(author = "2385601060@qq.com")
	@GetMapping("/shortest-path")
	@ApiOperation(value = "最短路径分析", notes = "根据起点和终点坐标计算最短路径")
	public ResponseEntity<String> shortestPath(
			@RequestParam(name = "start", defaultValue = "13219118.287269,3770416.81657993") String start,
			@RequestParam(name = "end", defaultValue = "13209838.7389836,3771149.73358722") String end) {

		log.info("开始路径分析: start={}, end={}", start, end);

		// 解析经纬度
		double[] startCoords = parseCoordinates(start);
		double[] endCoords = parseCoordinates(end);
		try {
			String result = iShapefileService.shortestPath(startCoords, endCoords);

			return ResponseEntity.ok()
					.contentType(MediaType.APPLICATION_JSON)
					.body(result);
		} catch (Exception e) {
			log.error("路径分析失败", e);
			return ResponseEntity.status(500).body("{\"error\": \"路径分析失败：" + e.getMessage() + "\"}");

		}
	}

	// 解析坐标字符串为数组
	private double[] parseCoordinates(String coords) {
		String[] parts = coords.split(",");
		if (parts.length != 2) throw new IllegalArgumentException("坐标格式错误");
		return new double[]{
				Double.parseDouble(parts[0]),
				Double.parseDouble(parts[1])
		};
	}

}


